package com.meixiang.activity.account.myAppointment;

import android.Manifest;
import android.annotation.TargetApi;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.lzy.okhttputils.model.HttpParams;
import com.meixiang.R;
import com.meixiang.activity.account.myShopper.PhotoFileEvaluateActivity;
import com.meixiang.adapter.personalCenter.OrderEvaluationPhotoAdapter;
import com.meixiang.dialog.SelectDialog;
import com.meixiang.entity.EvaluateGradle;
import com.meixiang.global.Config;
import com.meixiang.global.GlobalConventionalData;
import com.meixiang.global.GlobalType;
import com.meixiang.http.HttpCallBack;
import com.meixiang.http.HttpUtils;
import com.meixiang.main.BaseActivity;
import com.meixiang.main.MXApplication;
import com.meixiang.tool.Tool;
import com.meixiang.util.AbFileUtils;
import com.meixiang.util.AbStrUtil;
import com.meixiang.util.AbToastUtil;
import com.meixiang.view.ClearEditText;
import com.meixiang.view.TitleView;
import com.meixiang.view.photoSelectActivity.util.Bimp;
import com.meixiang.view.pickerView.OptionsPickerView;
import com.zhy.m.permission.MPermissions;
import com.zhy.m.permission.PermissionDenied;
import com.zhy.m.permission.PermissionGrant;

import org.json.JSONArray;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * @author xyj
 *         预约 申请退款页面
 */
@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
public class AppointmentSaleActivity extends BaseActivity {
    @Bind(R.id.title)
    TitleView title;
    @Bind(R.id.appointment_sale_tv_select_reason)
    TextView tv_select_reason ; //退款原因
    @Bind(R.id.appointment_clear_edittext)
    EditText clear_edittext ; //金额输入框、
    @Bind(R.id.appointment_sale_et_problem_details)
    ClearEditText sale_et_problem_details ; //描述输入框
    @Bind(R.id.appointment_sale_linear_photo_printing)
    LinearLayout linear_photo_printing ; //添加图片按钮
    @Bind(R.id.order_sale_recycler)
    RecyclerView recyclerView ;
    @Bind(R.id.appointment_sale_bt_commit)
    Button bt_commit ; //提交申请按钮
    private OptionsPickerView mOptionsPickerView ;
    private ArrayList<String> customList;
    private String orderId, typeId, reasonId, reasonInfo, orderName,refundAmount;
    private ArrayList<HashMap<String, String>> reasons;
    private ArrayList<String> imageList;
    private OrderEvaluationPhotoAdapter gridAdapter;
    private static final int CAMERA_CODE = 0x00; // 拍照的权限
    private File imgFile;//相机拍照存放地址
    private DeleteSelectPhotoBroad broadCast;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        setContentView(R.layout.activity_appointment_sale);
        ButterKnife.bind(this);
        super.onCreate(savedInstanceState);
    }

    @Override
    protected void initTitle() {
        setTitle("申请退款");
    }

    @Override
    protected void initView() {
        orderId=getIntent().getStringExtra("orderId");
        typeId = getIntent().getStringExtra("typeId");
        orderName = getIntent().getStringExtra("orderName");
        refundAmount=getIntent().getStringExtra("refundAmount");
        clear_edittext.setText(refundAmount);
        tv_select_reason.setOnClickListener(this);
        linear_photo_printing.setOnClickListener(this);
        bt_commit.setOnClickListener(this);
        gridAdapter=new OrderEvaluationPhotoAdapter(context,orderName);
        GridLayoutManager gridLayoutManager=new GridLayoutManager(context,4);
        recyclerView.setLayoutManager(gridLayoutManager);
        recyclerView.setAdapter(gridAdapter);
        registerBroadCast();
    }

    private void registerBroadCast(){
        broadCast=new DeleteSelectPhotoBroad();
        IntentFilter intentFilter=new IntentFilter(GlobalType.EVALUATE_ORDER_DELETE_PHOTO);
        registerReceiver(broadCast, intentFilter);
    }

    @Override
    protected void setData() {
        imageList=new ArrayList<>();
        refundReason();
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()){
            case R.id.appointment_sale_tv_select_reason:
                if(reasons!=null&&reasons.size()>0){
                    mOptionsPickerView.show();
                }else{
                    Tool.showTextToast(context,"未获取退款原因");
                }
                break ;

            case R.id.appointment_sale_linear_photo_printing: //晒图
                if(imageList.size()>=4){
                    Tool.showTextToast(context,"不能超过4张");
                    return;
                }
                new SelectDialog(context, new String[]{"拍照上传", "相册选择"}, new SelectDialog.IResultListener() {
                    @Override
                    public void SelectResult(int result) {

                        if (result == 0) {
                            //拍照
                            if (Build.VERSION.SDK_INT >= 23) {
                                MPermissions.requestPermissions(AppointmentSaleActivity.this, CAMERA_CODE, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA});
                            }else{
                                photoGraph();
                            }
                        } else {
                            //手机相册
                            localImage();
                        }
                    }
                });
                break;
            case R.id.appointment_sale_bt_commit: //提交申请
                submitApply();
                break ;
        }
    }

    private void localImage() {
        Intent intent = new Intent(context,PhotoFileEvaluateActivity.class);
//        intent.putExtra("photoType", "");
        if(imageList.size()>0){
            intent.putExtra("selectImageSize",imageList.size());
        }
        startActivityForResult(intent,100);

    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==100&&resultCode==200){
            //相册选择
            ArrayList<String> fileName = data.getStringArrayListExtra("fileName");
            imageList.addAll(fileName);
            gridAdapter.addPhoto(imageList);
        }else if(requestCode==101&&resultCode==RESULT_OK){
            //拍照
            String path = imgFile.getAbsolutePath();
            imageList.add(path);
            gridAdapter.addPhoto(imageList);

        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        MPermissions.onRequestPermissionsResult(this, requestCode, permissions, grantResults);
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
    @PermissionGrant(CAMERA_CODE)
    public void requestSdcardSuccess() {
        photoGraph();
    }

    @PermissionDenied(CAMERA_CODE)
    public void requestSdcardFailed() {
        Toast.makeText(activity, "无法启动系统照相机!", Toast.LENGTH_SHORT).show();
    }

    private class DeleteSelectPhotoBroad extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            int position=intent.getIntExtra("position",0);
//            int orderPosition=intent.getIntExtra("orderPosition",0);
            gridAdapter.deletePhoto(position);


        }
    }

    private void photoGraph() {
        //判断内存卡是否存在
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            //创建文件夹
            File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
            //判断是否存在，不存在则创建
            if (!mFolder.exists()) {
                mFolder.mkdirs();
            }
            //删除存在的照片
            File files[] = mFolder.listFiles(); // 声明目录下所有的文件 files[];
            for (int i = files.length - 1; i >= 0; i--) { // 遍历目录下所有的文件
                files[i].delete();// 删除
            }
            //创建新的照片
            String imgName = "mx_" + System.currentTimeMillis() + ".png";
            imgFile = new File(mFolder, imgName);
            //打开相机
            Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//            captureIntent.putExtra(MediaStore.Images.Media.ORIENTATION, 0);
            //保存路径
            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(imgFile));
            Log.e("TAG","输出照相路径==="+Uri.fromFile(imgFile));
            startActivityForResult(captureIntent, 101);
        } else {
            AbToastUtil.showToast(context, context.getResources().getString(R.string.account_manage_no_sd_card));
        }

    }


    @SuppressWarnings("unchecked")
    private OptionsPickerView initPickerView(final ArrayList<HashMap<String, String>> reasons) {
        customList = new ArrayList<>();
        //选项选择器
        mOptionsPickerView = new OptionsPickerView(this);
        for (int i = 0; i < reasons.size(); i++) {
            HashMap<String, String> reasonList = reasons.get(i);
            Iterator<Map.Entry<String, String>> iterator = reasonList.entrySet().iterator();
            while (iterator.hasNext()) {
                Map.Entry<String, String> next = iterator.next();
                customList.add(next.getValue());
            }
        }

        //一级
        mOptionsPickerView.setPicker(customList);
        mOptionsPickerView.setTitle("退款原因");
        mOptionsPickerView.setCyclic(false);
        //设置默认选中的三级项目
        //监听确定选择按钮
        mOptionsPickerView.setSelectOptions(1);
        mOptionsPickerView.setOnoptionsSelectListener(new OptionsPickerView.OnOptionsSelectListener() {

            @Override
            public void onOptionsSelect(int options1, int option2, int options3) {
                HashMap<String, String> selectReason = reasons.get(options1);
                Iterator<Map.Entry<String, String>> iterator = selectReason.entrySet().iterator();
                while (iterator.hasNext()) {
                    Map.Entry<String, String> next = iterator.next();
                    Log.e("OrderSale", next.getKey() + "===退款选择原因===" + next.getValue());
                    reasonId = next.getKey();
                    reasonInfo = next.getValue();
                    tv_select_reason.setText(next.getValue());

                }
            }
        });
        return mOptionsPickerView;
    }

    private void uploadImage(String refundId){
        String url=Config.SERVER_URL+"refund/imageFileReceive";
        HttpParams params=new HttpParams();
        params.put("refundId",refundId);
        if(imageList.size()>0){
            List<File> fileList=new ArrayList<>();
            for(int i=0;i<imageList.size();i++){
                File compressFile = getCompressFile(imageList.get(i));
                if(compressFile!=null){
                    fileList.add(new File(imageList.get(i)));
                }
            }
            HttpUtils.postFiles(url, params, "imageFile", fileList, new HttpCallBack(this) {
                @Override
                public void onSucceed(JSONObject result, String code, String message) {
//                    Tool.showTextToast(context,message);
                }

                @Override
                public void onError(String code, String message) {
                    Tool.showTextToast(context,message);
                }
            });
        }
    }

    /**
     * 压缩图片上传
     * @param file1
     * @return
     */
    private File getCompressFile(String file1){
        Log.e(TAG,"文件大小==="+ AbFileUtils.getFileSizeFor(new File(file1)));
        try {
            Bitmap bitmap = Bimp.revitionImageSize(file1);
            if(bitmap==null){
                Log.e(TAG,"图片转bitmap失败");
                return null;
            }else{
                Log.e(TAG,"图片转bitmap成功");
                Bitmap bitmap1 = AbFileUtils.compressImage(bitmap);
                //创建新的照片
                File mFolder = new File(Environment.getExternalStorageDirectory(), Config.base_data_path + "/mx");
                String imgName = mFolder.getAbsolutePath()+"mx" + System.currentTimeMillis() + ".png";
                File file = AbFileUtils.saveFile(bitmap1, imgName);
                Log.e(TAG,"上传文件大小==="+AbFileUtils.getFileSizeFor(file));
                return file;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(broadCast);
    }

    /**
     * 刷新订单列表
     */
    private void notifyOrderList(){
        Intent intent=new Intent(GlobalType.APPOINTMENT_DETIAL);
        sendBroadcast(intent);
        this.finish();
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if(event.getKeyCode()==KeyEvent.KEYCODE_BACK){
            if(mOptionsPickerView!=null&&mOptionsPickerView.isShowing()){
                mOptionsPickerView.dismiss();
                return true;
            }else{
                this.finish();
            }
        }
        return true;

    }

    /**
     * 提交退款申请
     */
    private void submitApply(){
        if(TextUtils.isEmpty(reasonInfo)){
            AbToastUtil.showToast(context,"请选择退款原因");
            return ;
        }
        if (TextUtils.isEmpty(clear_edittext.getText().toString())){
            AbToastUtil.showToast(context,"请输入退款金额");
            return;
        }
        if (TextUtils.isEmpty(sale_et_problem_details.getText().toString())){
            AbToastUtil.showToast(context,"请输入退款描述");
            return;
        }

        HttpParams httpParams = new HttpParams();
        httpParams.put("orderInfo",sale_et_problem_details.getText().toString()); // 退款描述
        httpParams.put("refundAmount",clear_edittext.getText().toString()); // 退款金额
        httpParams.put("refundReason",reasonInfo); // 退款理由
        httpParams.put("reasonId",reasonId); // 退款理由Id
        httpParams.put("orderId",orderId);
        HttpUtils.post(Config.SERVICE_ORDER_REFUND_SUBMITAPPLY, httpParams, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                Tool.showTextToast(context,message);
                if(result!=null){
                    String refundId=result.optString("returnId");
                    if(!AbStrUtil.isEmpty(refundId)){
                        uploadImage(refundId);
                    }
                }
                notifyOrderList();
                AppointmentSaleActivity.this.finish();
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });
    }

    /**
     * 获取退款理由
     */
    private void refundReason(){
        reasons = new ArrayList<>();
        HttpParams httpParams = new HttpParams();
        httpParams.put("typeId",typeId);
        HttpUtils.post(Config.SERVICE_ORDER_REFUND_REASON, httpParams, new HttpCallBack(this) {
            @Override
            public void onSucceed(JSONObject result, String code, String message) {
                JSONArray refundReasonList = result.optJSONArray("refundReasonList");
                for (int i = 0; i < refundReasonList.length(); i++) {
                    HashMap<String, String> reason = new HashMap<>();
                    JSONObject jsonObject = refundReasonList.optJSONObject(i);
                    String reasonId = jsonObject.optString("reasonId");
                    String reasonInfo = jsonObject.optString("reasonInfo");
                    reason.put(reasonId, reasonInfo);
                    reasons.add(reason);
                    initPickerView(reasons);
                }
            }

            @Override
            public void onError(String code, String message) {
                Tool.showTextToast(context,message);
            }
        });
    }
}
